//
//  LLTextView.swift
//  LaiLang
//
//  Created by David on 2017/2/17.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class LLTextView: UITextView, UITextViewDelegate {
    
    var placeholder: String?{
        get{
            return placeholderView.text
        }
        set(v){
            placeholderView.text = v
            
        }
    }
    
    var placeholderView: UITextView!
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        delegate = self
        
        placeholderView = UITextView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
        placeholderView.textColor = UIColor.gray
        placeholderView.isEditable = false
        placeholderView.isSelectable = false
        insertSubview(placeholderView, at: 0)
    }
    
    convenience init(frame: CGRect){
        self.init(frame: frame, textContainer: nil)
    }
    
    
    
    func textViewDidChange(_ textView: UITextView) {
        if textView.text != "" {
            placeholderView.alpha = 0
        }else{
            placeholderView.alpha = 1
        }
    }
    
    var maxLength: Int = -1
    
    private var _weakDelegate: UITextViewDelegate?
    var weakDelegate: UITextViewDelegate?{
        get{
            return _weakDelegate
        }
        set(d){
            _weakDelegate = d
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        _ = _weakDelegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text)
        if maxLength >= 0{
            
            if textView.text != nil {
                let strLen = textView.text!.characters.count
                if (range.length + range.location > strLen){
                    return false
                }
                let newLength = strLen + text.characters.count - range.length
                return newLength <= maxLength
            }
            
        }
        return true
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        _weakDelegate?.textViewDidBeginEditing?(textView)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
